package com.ruoyi.business.utils;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.business.domain.SysUserLoginCompany;
import com.ruoyi.business.mapper.SysUserLoginCompanyMapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import java.time.Instant;

/**
 * 订单工具类
 */
public class OrderUtils {


    /**
     * 生成订单号
     * 客户名称拼音简写（4位）+月日（4位）+当日该用户订序号（2位）
     */
    public static String generateOrderNo(Long userId) {
        SysUserLoginCompanyMapper companyMapper = SpringUtils.getBean(SysUserLoginCompanyMapper.class);
        if (companyMapper == null) {
            throw new ServiceException("生成订单号失败");
        }
        SysUserLoginCompany company = companyMapper.selectByUserId(userId);
        if (company == null) {
            throw new ServiceException("生成订单号失败");
        }
        String companyAbbreviation = company.getCompanyAbbreviation();
        if (StrUtil.isEmpty(companyAbbreviation)) {
          companyAbbreviation=String.valueOf(generateRandomNumber(company.getCompanyName()));
        }
        Long orderSerial = RedisUtils.setCacheMapIncrement(CacheConstants.ORDER_SERIAL_KEY, String.valueOf(company.getDriverId()), 1);
        return companyAbbreviation + DateUtils.dateTimeNow("MMdd") + String.format("%02d", orderSerial);
    }

    /**
     * 生成运单号
     * 客户名称拼音简写（4位）+月日（4位）+ 当日该用户订序号（2位）+ Y + 两位序号。
     */
    public static String generateWaybillNo(Long userId) {
        SysUserLoginCompanyMapper companyMapper = SpringUtils.getBean(SysUserLoginCompanyMapper.class);
        if (companyMapper == null) {
            throw new ServiceException("生成订单号失败");
        }
        SysUserLoginCompany company = companyMapper.selectByUserId(userId);
        if (company == null) {
            throw new ServiceException("生成订单号失败");
        }
        String companyAbbreviation = company.getCompanyAbbreviation();
        if (StrUtil.isEmpty(companyAbbreviation)) {
            companyAbbreviation=String.valueOf(generateRandomNumber(company.getCompanyName()));
        }
        Long orderSerial = RedisUtils.setCacheMapIncrement(CacheConstants.ORDER_SERIAL_KEY, String.valueOf(company.getDriverId()), 1);
        Long waybillSerial = RedisUtils.setCacheMapIncrement(CacheConstants.WAYBILL_SERIAL_KEY, String.valueOf(company.getDriverId()), 1);
        return companyAbbreviation + DateUtils.dateTimeNow("MMdd") + String.format("%02d", orderSerial) + "Y" + String.format("%02d", waybillSerial);
    }

    /**
     * 生成与字符串关联的随机数
     */
    public static int generateRandomNumber(String companyName) {
        // 随机名称
        if (StrUtil.isEmpty(companyName)) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < 5; i++) {
                builder.append(RandomUtil.randomChinese());
            }
            companyName = builder.toString();
        }

        // 确保至少取四个字符，如果公司名不足四个字符则取全部
        String featureSubstring = companyName.substring(0, Math.min(4, companyName.length()));

        // 计算特征字符串中所有字符的ASCII码之和
        int asciiSum = 0;
        for (char ch : featureSubstring.toCharArray()) {
            asciiSum += ch;
        }

        // 结合当前时间的毫秒数以增加随机性
        long currentTimeMillis = Instant.now().toEpochMilli();

        // 使用ASCII码之和与当前时间的组合生成种子
        long seed = asciiSum + currentTimeMillis;

        // 使用seed生成一个伪随机数
        java.util.Random random = new java.util.Random(seed);

        // 生成0-9999之间的随机数
        int randomNumber = random.nextInt(10000);

        // 确保生成的随机数为四位数
        return randomNumber < 1000 ? randomNumber + 1000 : randomNumber;
    }
}
